import Router from 'vue-router'
import routes from './routes'
import store from '@/store'

let orignPush = Router.prototype.push;

Router.prototype.push = function(location, resolve, reject, ) {
   if (resolve & reject) {
      orignPush.call(this, location, resolve, reject);
   }else {
      orignPush.call(this, location, () => {}, ()=>{});
   }
}

const router = new Router ({
   routes,
});

router.beforeEach(async (to, from, next) => {
   let token = store.state.user.token;
   // 如果用户已经登录
   if (token) {
      // 如果 要去登录页面
      if (to.path == '/login') {
         // 不放行
         next('/');
         console.log('路由守卫');
      }else {
         // 登录了，但是还没有用户信息
         if (!store.state.user.userInfo.nickName) {
            // 请求用户信息
            try {
               await store.dispatch('user/getUserInfo');
               next();
            } catch (error) {
               // 如果token失效了，请求不到
               // 退出登录，清除token
               store.dispatch('getLogout');               
            }
         }
         next();// 放行
      }
   }else {
      // 如果没登陆
      let toPath = to.path;
      if (toPath != '/login') {
         next('/login?redirect=' + toPath);
      }else {
         let toPath = '/' + to.query.redirect
            next('/' + to.query.redirect);
      }
   }
})

export default router;